<template>
  <div id="handleDialog">
    <el-dialog
      width="800px"
      :title="handleDialogData.title"
      :visible.sync="handleDialogData.isShow"
    >
      <div class="title">分享图片配置</div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label-width="120px" label="小程序分享卡片" required>
          <div class="upcontent">
            <div class="contai">
              <el-form-item prop="shareImage">
                <div>
                  <div class="cover-container">
                    <img
                      v-if="ruleForm.shareImage"
                      class="cover-img"
                      :src="ruleForm.shareImage"
                      alt="小程序分享卡片"
                    />
                  </div>
                  <el-button
                    class="upload-btn"
                    @click="uploadCoverImg('shareImage')"
                    >上传</el-button
                  >
                  <el-button @click="deleteImg('shareImg')" class="deletedbtn"
                    >删除</el-button
                  >
                </div>
              </el-form-item>
              <div class="introduce">封面图片：小程序分享卡片封面图</div>
              <div class="introduce">您可以上传jpg,png格式的文件。</div>
              <div class="introduce">
                文件大小不能超过20MB，推荐图片大小为630*544
              </div>
            </div>
            <el-form-item prop="shareTitle">
              <div class="textarea">
                <el-input
                  v-model="ruleForm.shareTitle"
                  placeholder="请输入分享标题"
                  auto-size
                  :allowClear="true"
                  :rows="4"
                  :maxLength="26"
                />
                <div class="introduce">分享语不要超过26个字，包含标点</div>
              </div>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label-width="120px" label="海报封面图" required>
          <div class="upcontent">
            <div class="contai">
              <el-form-item prop="poster">
                <div>
                  <div class="cover-containerto">
                    <img
                      v-if="ruleForm.poster"
                      class="cover-img"
                      :src="ruleForm.poster"
                      alt="海报封面图"
                    />
                  </div>
                  <el-button
                    class="upload-btn"
                    @click="uploadCoverImg('poster')"
                    >上传</el-button
                  >
                  <el-button @click="deleteImg('posterImg')" class="deletedbtn"
                    >删除</el-button
                  >
                </div>
              </el-form-item>
              <div class="introduce">海报图片：课程海报背景图</div>
              <div class="introduce">您可以上传jpg,png格式的文件。</div>
              <div class="introduce">
                文件大小不能超过20MB，推荐图片大小为288*513
              </div>
            </div>
            <el-form-item prop="posterTitle">
              <div class="textarea">
                <el-input
                  v-model="ruleForm.posterTitle"
                  placeholder="请输入海报封面标题"
                  auto-size
                  :allowClear="true"
                  :rows="4"
                  :maxLength="26"
                />
                <div class="introduce">海报标题不要超过26个字，包含标点</div>
              </div>
            </el-form-item>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleCancel" plain>取 消</el-button>
        <el-button type="success" @click="handleOk('ruleForm')">确定</el-button>
      </span>
    </el-dialog>
    <ImgCutter
      class="cutDownImg"
      ref="imgCutterModal"
      :cross-origin="true"
      :is-modal="true"
      :show-choose-btn="true"
      :lock-scroll="true"
      :box-width="1000"
      :box-height="600"
      :cut-width="imgWidth"
      :cut-height="imgHeight"
      :size-change="true"
      :move-able="true"
      @cutDown="cutDown"
    >
      <span slot="open"></span>
    </ImgCutter>
  </div>
</template>
<script>
import {
  uploadImg,
  updateChaptersDetail,
  updateCollegeDetail
} from '@/api/applet'
import ImgCutter from 'vue-img-cutter'
import { dataURLtoBlob } from '@/utils/validate'
export default {
  props: {
    handleDialogData: {
      type: Object,
      default: () => {
        return {
          isShow: false,
          params: '',
          type: '',
          title: ''
        }
      }
    }
  },
  components: { ImgCutter },
  data() {
    return {
      form: {},
      ruleForm: {
        shareTitle: '', // 分享标题
        posterTitle: '', // 海报标题
        poster: '', // 海报图
        shareImage: '' // 分享图
      },
      shareFile: null,
      posterFile: null,
      file: null,
      imgWidth: 630,
      imgHeight: 544,
      rules: {
        poster: [
          { required: true, message: '请上传海报封面图片', trigger: 'change' }
        ],
        shareImage: [
          { required: true, message: '请上传分享图片', trigger: 'change' }
        ],
        shareTitle: [
          { required: true, message: '请输入分享标题', trigger: 'blur' },
          {
            min: 0,
            max: 26,
            message: '分享语超过26个字，请重新编辑',
            trigger: 'change'
          }
        ],
        posterTitle: [
          { required: true, message: '请输入海报封面标题', trigger: 'blur' },
          {
            min: 0,
            max: 26,
            message: '分享语超过26个字，请重新编辑',
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted() {
    this.ruleForm.shareTitle = this.handleDialogData.params.shareTitle
    this.ruleForm.posterTitle = this.handleDialogData.params.posterTitle
    this.ruleForm.poster = this.handleDialogData.params.poster
    this.ruleForm.shareImage = this.handleDialogData.params.shareImage
  },
  methods: {
    // 打开图片裁剪工具
    uploadCoverImg(target) {
      if (target === 'shareImage') {
        ;[this.imgWidth, this.imgHeight] = [630, 544]
      } else {
        ;[this.imgWidth, this.imgHeight] = [288, 513]
      }
      this.currentTarget = target
      this.$refs.imgCutterModal.handleOpen()
    },
    // 裁剪事件
    cutDown(res) {
      this.coverUpload(res.file)
    },
    // 封面图上传
    coverUpload(file) {
      const targetImg = this.currentTarget
      const _this = this
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return false
      }
      _this.file = file
      if (file) {
        var reader = new FileReader()
        // 上传成功后，将本地的默认图替换为上传成功的图片
        if (targetImg === 'poster') {
          reader.onload = function(event) {
            _this.posterFile = window.URL.createObjectURL(
              dataURLtoBlob(event.target.result)
            )
          }
        } else if (targetImg === 'shareImage') {
          reader.onload = function(event) {
            _this.shareFile = window.URL.createObjectURL(
              dataURLtoBlob(event.target.result)
            )
          }
        }
      }
      reader.readAsDataURL(file)
      this.handleUploading(targetImg)
    },
    handleUploading(targetImg) {
      let formData = new FormData()
      formData.append('file', this.file)
      uploadImg(
        formData,
        (response) => {
          if (targetImg === 'poster') {
            this.ruleForm.poster = response[0].url
          } else if (targetImg === 'shareImage') {
            this.ruleForm.shareImage = response[0].url
          }
        },
        (response) => {
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    // 点击确定
    handleOk(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.handleDialogData.type === 'edit') {
            let data = {
              updateList: {
                finishTime: this.handleDialogData.params.finishTime,
                liveChannelId: this.handleDialogData.params.liveChannelId,
                ordered: this.handleDialogData.params.ordered,
                poster: this.ruleForm.poster,
                posterTitle: this.ruleForm.posterTitle,
                shareImage: this.ruleForm.shareImage,
                shareTitle: this.ruleForm.shareTitle,
                startTime: this.handleDialogData.params.startTime,
                status: this.handleDialogData.params.status,
                teacherId: this.handleDialogData.params.teacherId,
                title: this.handleDialogData.params.title
              },
              chapterId: this.handleDialogData.params.id,
              courseId: this.handleDialogData.params.courseId
            }
            updateChaptersDetail(
              data,
              (response) => {
                this.$message.success(
                  this.handleDialogData.params.title + '配置修改成功！'
                )
                this.handleDialogData.isShow = false
                this.$emit('refreshList')
              },
              (response) => {
                this.$message({
                  message: response.message,
                  type: 'warning'
                })
              }
            )
          } else {
            let data = {
              collegeId: this.handleDialogData.params.id,
              updateList: {
                gradeId: this.handleDialogData.params.gradeId,
                name: this.handleDialogData.params.name,
                ordered: this.handleDialogData.params.ordered,
                parentId: this.handleDialogData.params.parentId,
                poster: this.ruleForm.poster,
                posterTitle: this.ruleForm.posterTitle,
                shareImage: this.ruleForm.shareImage,
                shareTitle: this.ruleForm.shareTitle,
                status: this.handleDialogData.params.status
              }
            }
            updateCollegeDetail(
              data,
              (response) => {
                this.$message.success(
                  this.handleDialogData.title + '修改成功！'
                )
                this.handleDialogData.isShow = false
                this.$emit('refreshList')
              },
              (response) => {
                this.$message({
                  message: response.message,
                  type: 'warning'
                })
              }
            )
          }
        } else {
          return false
        }
      })
    },
    // 点击取消
    handleCancel() {
      this.handleDialogData.isShow = false
    },
    // 删除封面图
    deleteImg(targetImg) {
      if (targetImg === 'posterImg') {
        this.ruleForm.poster = ''
      } else if (targetImg === 'shareImg') {
        this.ruleForm.shareImage = ''
      }
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-form-item__label) {
  width: auto !important;
}
.upcontent {
  display: flex;
  justify-content: space-between;
}
.cover-container {
  background: #dedede;
  height: 272px;
  width: 315px;
  text-align: center;
  box-sizing: border-box;
  .cover-img {
    width: 100%;
    height: 100%;
    vertical-align: middle;
  }
}
.cover-containerto {
  background: #dedede;
  height: 513px;
  width: 288px;
  margin-right: 30px;
  text-align: center;
  box-sizing: border-box;
  .cover-img {
    width: 100%;
    height: 100%;
    vertical-align: middle;
  }
}
.deletedbtn {
  color: #ffff;
  background-color: red;
}
.upload-btn {
  color: #fff;
  background-color: #1890ff;
}
.title {
  margin-bottom: 15px;
}
.introduce {
  margin-top: 10px;
}
.cutDownImg {
  position: fixed;
  z-index: 3000;
}
</style>
